/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.prod;



import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.AlmacenXProducto;
import dp1.titandevelop.titano.persistent.Asignacion;
import dp1.titandevelop.titano.persistent.EmpleadoXProcesoTurno;
import dp1.titandevelop.titano.persistent.OrdenProduccion;
import dp1.titandevelop.titano.persistent.Produccion;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.persistent.Receta;
import dp1.titandevelop.titano.service.AlmacenService;
import dp1.titandevelop.titano.service.EmpleadoXProcesoTurnoService;
import dp1.titandevelop.titano.service.OrdenProduccionService;
import dp1.titandevelop.titano.service.ProduccionService;
import dp1.titandevelop.titano.service.ProductoXProcesoService;
import dp1.titandevelop.titano.service.RecetaService;
import dp1.titandevelop.titano.service.ValidacionService;
import dp1.titandevelop.titano.view.MensajeError;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author chrestean
 */
public class ModulosT_PRO_ProduccionNuevo extends javax.swing.JInternalFrame {

     ProduccionService s;
    EmpleadoXProcesoTurnoService sept;
    AlmacenService sa= new AlmacenService();
    RecetaService sr = new RecetaService();
    ArrayList<EmpleadoXProcesoTurno> ept;
    ArrayList<Produccion> listaProduccion;  
    ArrayList<AlmacenXProducto> listaAlm;
    private Mensajes sms = new Mensajes();
    
    /**
     * Creates new form TitanoInteralSegADMUser
     */
    //Refrescar la tabla de productos
    public void RefrescarTabla() {
        
        AbstractTableModel aux = (AbstractTableModel) tblProduccion.getModel();
           // this.inhabilitaBotones();
        aux.fireTableDataChanged();
        }
    
     public boolean verificaStock(Producto prod1, float produccion, float rotura)
    {
        ArrayList<AlmacenXProducto> listaAlmAux= new ArrayList<AlmacenXProducto>();
        if (listaAlm.isEmpty())
            return false;
        for (int i=0; i<listaAlm.size();i++)//copia lista
        {
            AlmacenXProducto a= new AlmacenXProducto();
            a.setCapacidad(listaAlm.get(i).getCapacidad());
            a.setEstado(listaAlm.get(i).getEstado());
            a.setIdalmacenxproducto(listaAlm.get(i).getIdalmacenxproducto());
            a.setStock(listaAlm.get(i).getStock());
            a.setToAlmacen(listaAlm.get(i).getToAlmacen());
            a.setToProducto(listaAlm.get(i).getToProducto());
            listaAlmAux.add(a);
        }
        ArrayList<Receta> rr= this.sr.BuscarPorProducto(prod1);
        for (int i=0; i<rr.size(); i++)
        {
            int idMaterial= rr.get(i).getToProducto1().getIdproducto();
            int cantidad= Math.round(rr.get(i).getCantidad()*produccion+rr.get(i).getCantidad()*rotura);
            for (int j=0; j<listaAlmAux.size(); j++)
            {
                int idProducto = listaAlmAux.get(j).getToProducto().getIdproducto();
                if (idMaterial == idProducto)
                {
                    int stock = listaAlmAux.get(j).getStock();
                    if (cantidad>stock)
                        return false;
                    else 
                        listaAlmAux.get(j).setStock(stock-cantidad);
                }
            }
        }
        return true;
    }



    public void AgregaProduccion(EmpleadoXProcesoTurno e, Asignacion a, float prod, float rotura ) {
        //Verifica stock!!!
       ProductoXProcesoService spp = new ProductoXProcesoService();
       Producto prod1= spp.DevueveSalida(a.getToProducto().getIdproducto(), a.getToMaquina().getToProceso().getIdproceso());
       //if (prod> 700){
       if (!verificaStock(prod1, prod, rotura)){
             JOptionPane.showInternalMessageDialog(this.getRootPane(),"No es posible completar la solicitud, no hay suficiente stock",
                     "Aviso!",JOptionPane.WARNING_MESSAGE);
        }
       
        else{
            //Inserta produccion
            Produccion p = new Produccion ();
            p.setToAsignacion(a);
            p.setProductividad(prod);
            p.setRotura(rotura);        
            //calcular beneficio y costo.       
            p.setBeneficio(prod*a.getToProducto().getBeneficio());
            p.setCosto((prod+rotura)*a.getToProducto().getCosto());
            listaProduccion.add(p);     
            ept.add(e);
        }
    }

    private AbstractTableModel modelo = new AbstractTableModel() {
        public int getRowCount() {
            if (listaProduccion!=null)
            return listaProduccion.size();
            else return 0;
        }

        public int getColumnCount() {
        return 7;
        }

        String [] titles = {"Operario","Turno","Proceso","Prod. Real", "Rot. Real", "Prod. Teorica", "Rot. Teorica"};

        @Override
        public String getColumnName(int col){
        return titles[col];
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
        //String res=null;
        Produccion p=listaProduccion.get(rowIndex);
            switch (columnIndex){
            case 0: return p.getToAsignacion().getToEmpleado().getNombres()+ " "+p.getToAsignacion().getToEmpleado().getApellidop();
            case 1: return p.getToAsignacion().getToTurno().getDescripcion();
            case 2: return p.getToAsignacion().getToMaquina().getToProceso().getDescripcion();
            case 3: return p.getProductividad();
            case 4: return p.getRotura();
            case 5: return ept.get(rowIndex).getProductividad();
            case 6: return ept.get(rowIndex).getRotura();
            }
            return null;
            } 
    };
    
     public ModulosT_PRO_ProduccionNuevo() {
        initComponents();
        this.sept = new EmpleadoXProcesoTurnoService();
        ept= new ArrayList<EmpleadoXProcesoTurno>();
        listaAlm = new ArrayList<AlmacenXProducto>();
        this.listaAlm.addAll(this.sa.obtenerTemporal());
        ValidacionService vs = new ValidacionService();
        vs.NoEscribe(this.txtFecha);
        Date d=new Date();
        txtFecha.setDate(new Date(d.getTime()));
        s = new ProduccionService();
        this.tblProduccion.setModel(this.modelo); 
        listaProduccion= new ArrayList<Produccion>();
       
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblFecha = new javax.swing.JLabel();
        txtFecha = new org.jdesktop.swingx.JXDatePicker();
        jLabel1 = new javax.swing.JLabel();
        txtDescripcion = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblProduccion = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        btnDetalle = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setResizable(true);
        setTitle("Nueva Producción");
        setPreferredSize(new java.awt.Dimension(700, 390));
        setRequestFocusEnabled(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtros de Búsqueda"));
        jPanel1.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        lblFecha.setText("Fecha de Produccion");

        jLabel1.setText("Descripcion");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(lblFecha)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblFecha)
                    .addComponent(jLabel1)
                    .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Productos"));
        jPanel2.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        tblProduccion.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Proceso", "Operario", "Producto", "Produccion", "Merma"
            }
        ));
        jScrollPane1.setViewportView(tblProduccion);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        btnDetalle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        btnDetalle.setToolTipText("Buscar");
        btnDetalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetalleActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnDetalle, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(10, 10, 10))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btnDetalle)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addGap(18, 18, 18))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnDetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetalleActionPerformed
        // TODO add your handling code here:
         ValidacionService vs = new ValidacionService();
         OrdenProduccionService so = new OrdenProduccionService();
         
     if (!vs.esVacio(this.txtDescripcion)) 
    {
       
        OrdenProduccion op = so.buscarEnProceso();
        if(op!=null){
             this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            ArrayList<Produccion> listaAux= s.buscarProduccionPorFecha(this.txtFecha.getDate());
            
            if(!listaProduccion.isEmpty()) listaAux.addAll(listaProduccion);

            try{
             Frame f = JOptionPane.getFrameForComponent(this);
             ModulosT_PRO_BuscarOperario dialog = new ModulosT_PRO_BuscarOperario(f,true, listaAux);
             
             dialog.setVisible(true);
             this.setCursor(Cursor.getDefaultCursor());
            } catch(Exception e) {
                JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
            }        
        }
        else{
            JOptionPane.showInternalMessageDialog(this.getRootPane(),"No se han aprobado movimientos para la producción","Aviso!",JOptionPane.WARNING_MESSAGE);
        }
    }
    else
        JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getCompletarCampos(),"Aviso!",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_btnDetalleActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
     Date d= new Date();
        if (this.txtFecha.getDate().after(d)|| this.txtFecha.getDate().getMonth()<d.getMonth())
     {
         JOptionPane.showInternalMessageDialog(this.getRootPane(),"Ingrese una fecha Valida", "Aviso", JOptionPane.WARNING_MESSAGE);
         
     }
     else
     {
        Mensajes m = new Mensajes();
        ValidacionService vs = new ValidacionService();
            
     if (vs.esVacio(this.txtDescripcion)){
         JOptionPane.showInternalMessageDialog(this.getRootPane(),m.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);
     }
     else
         if(this.listaProduccion.isEmpty()){
                      JOptionPane.showInternalMessageDialog(this.getRootPane(),m.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);
         }
         else{
         
        try{
            this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            s.Insertar(txtFecha.getDate(),listaProduccion,txtDescripcion.getText());  
            JOptionPane.showInternalMessageDialog(this.getRootPane(), m.getRegistrado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);
            
           ModulosT_PRO.admProduccion = new ModulosT_PRO_AdmPro();
        this.getParent().add(ModulosT_PRO.admProduccion);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = ModulosT_PRO.admProduccion.getSize();
        ModulosT_PRO.admProduccion.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
            (desktopSize.height - jInternalFrameSize.height)/4 );
        ModulosT_PRO.admProduccion.show();
         ModulosT_PRO.ventanaProduccionNuevo=null;
         this.setCursor(Cursor.getDefaultCursor());
        this.dispose();
            
           } catch(Exception e) {
               e.printStackTrace();
                JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
           }
     }
     }
       // s.Insertar(txtFecha.getDate(),listaProduccion, txtDescripcion.getText());        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        try{
        ModulosT_PRO.admProduccion = new ModulosT_PRO_AdmPro();
        this.getParent().add(ModulosT_PRO.admProduccion);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = ModulosT_PRO.admProduccion.getSize();
        ModulosT_PRO.admProduccion.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
            (desktopSize.height - jInternalFrameSize.height)/4 );
        ModulosT_PRO.admProduccion.show();
         ModulosT_PRO.ventanaProduccionNuevo=null;
        this.dispose();
        } catch(Exception e) {
            JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
        }
         
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        this.listaProduccion.remove(this.tblProduccion.getSelectedRow());
        this.ept.remove(this.tblProduccion.getSelectedRow());
        this.RefrescarTabla();
    }//GEN-LAST:event_jButton3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDetalle;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblFecha;
    private javax.swing.JTable tblProduccion;
    private javax.swing.JTextField txtDescripcion;
    private org.jdesktop.swingx.JXDatePicker txtFecha;
    // End of variables declaration//GEN-END:variables

    private void setLocationRelativeTo(Object object) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private Object getparent() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
